package me.baicai.modules.belldandy.gcb.service.impl;

import me.baicai.modules.belldandy.gcb.domain.Project;
import me.baicai.modules.belldandy.gcb.repository.ProjectRepository;
import me.baicai.modules.belldandy.gcb.repository.UserDividendRepository;
import me.baicai.modules.belldandy.gcb.repository.UserProjectRepository;
import me.baicai.modules.belldandy.gcb.service.ProjectService;
import me.baicai.modules.belldandy.gcb.service.dto.ProjectDTO;
import me.baicai.modules.belldandy.gcb.service.dto.ProjectQueryCriteria;
import me.baicai.modules.belldandy.gcb.service.mapper.ProjectMapper;
import me.baicai.utils.FileUtil;
import me.baicai.utils.PageUtil;
import me.baicai.utils.QueryHelp;
import me.baicai.utils.ValidationUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;


/**
 * @author 超级大白菜
 * @date 2020-03-31
 */
@Service
@CacheConfig(cacheNames = "project")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ProjectServiceImpl implements ProjectService
{

    private final ProjectRepository projectRepository;

    private final ProjectMapper projectMapper;

    private final UserProjectRepository userProject;

    private final UserDividendRepository userDividendRepository;

    public ProjectServiceImpl(ProjectRepository projectRepository, ProjectMapper projectMapper,
                              UserProjectRepository userProject,
                              UserDividendRepository userDividendRepository)
    {
        this.projectRepository = projectRepository;
        this.projectMapper = projectMapper;
        this.userProject = userProject;
        this.userDividendRepository = userDividendRepository;
    }

    @Override
    @Cacheable
    public Map<String, Object> queryAll(ProjectQueryCriteria criteria, Pageable pageable)
    {
        Page<Project> page = projectRepository.findAll(
            (root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria,
                criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(projectMapper::toDto));
    }

    @Override
    @Cacheable
    public List<ProjectDTO> queryAll(ProjectQueryCriteria criteria)
    {
        return projectMapper.toDto(projectRepository.findAll(
            (root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria,
                criteriaBuilder)));
    }

    @Override
    @Cacheable(key = "#p0")
    public ProjectDTO findById(Integer id)
    {
        Project project = projectRepository.findById(id).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", id);
        return projectMapper.toDto(project);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public ProjectDTO create(Project resources)
    {
        return projectMapper.toDto(projectRepository.save(resources));
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(Project resources)
    {
        Project project = projectRepository.findById(resources.getId()).orElseGet(Project::new);
        ValidationUtil.isNull(project.getId(), "Project", "id", resources.getId());
        project.copy(resources);
        projectRepository.save(project);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id)
    {
        projectRepository.deleteById(id);
    }

    @Override
    public void download(List<ProjectDTO> all, HttpServletResponse response)
        throws IOException
    {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProjectDTO project : all)
        {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("项目名称", project.getName());
            map.put("项目描述", project.getDescription());
            map.put("创建时间", project.getCeated());
            map.put("项目资金额", project.getAmount());
            map.put("项目收益", project.getIncome());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(Project resources)
    {
      userProject.deleteAllByPid(resources.getId());
      userProject.flush();
      userProject.saveAll(resources.getUserProject());
    }

    @Override
    public Object queryAll()
    {
        return projectRepository.findAll();
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void updateUserDividend(Project resources)
    {
        userDividendRepository.deleteAllByPid(resources.getId());
        userDividendRepository.flush();
        userDividendRepository.saveAll(resources.getUserDividend());
    }
}
